<template>
  <div>
    <div v-if="editOpen">
      <t-row style="align-items: stretch" :gutter="14">
        <t-col :span="12">
          <t-card class="step-card" size="small" title="承担单位">
            <t-table size="small" rowKey="id" :data="data5" :columns="phaseType !== '1' ? columns522 : columns52">
              <template #index="{ rowIndex }">
                {{ rowIndex + 1 }}
              </template>
              <template #isInnerCompany="{ row }">
                <t-switch size="large" v-model="row.isInnerCompany" :label="['是', '否']" :customValue="['1', '0']"
                  @change="() => { row.name = '' }"></t-switch>
              </template>
              <template #intro="{ row }">
                <t-textarea @change="() => { if (row.intro !== '') { row.introStatus = 'default' } }"
                  :status="row.introStatus" clearable :autosize="{ minRows: 3 }" v-model="row.intro">
                  <div slot="tips" v-if="row.introStatus === 'error'">不能为空</div>
                </t-textarea>
              </template>
              <template #leaderIntroduce="{ row }">
                <t-textarea
                  @change="() => { if (row.leaderIntroduce !== '') { row.leaderIntroduceStatus = 'default' } }"
                  :status="row.leaderIntroduceStatus" clearable :autosize="{ minRows: 3 }"
                  v-model="row.leaderIntroduce">
                  <div slot="tips" v-if="row.leaderIntroduceStatus === 'error'">不能为空</div>
                </t-textarea>
              </template>
              <template #division="{ row }">
                <t-textarea @change="() => { if (row.division !== '') { row.divisionStatus = 'default' } }"
                  :status="row.divisionStatus" clearable :autosize="{ minRows: 3 }" v-model="row.division">
                  <div slot="tips" v-if="row.divisionStatus === 'error'">不能为空</div>
                </t-textarea>
              </template>
            </t-table>
          </t-card>
        </t-col>
      </t-row>
      <t-row style="align-items: stretch" :gutter="14">
        <t-col v-if="site_tag === 'jtt'" :span="12">
          <t-card v-if="phaseType !== '1' || isShowTable" class="step-card" size="small">
            <template #title>
              合作单位 <span style="color:red;">（如有合作单位，请填写）</span>
            </template>
            <t-table size="small" rowKey="id" :selected-row-keys="selectedUnitRowKeys"
              @select-change="(val) => { selectedUnitRowKeys = val }" :data="data6"
              :columns="phaseType !== '1' ? columns53 : columns5">
              <template #index="{ rowIndex }">
                {{ rowIndex + 1 }}
              </template>
              <template #isInnerCompany="{ row }">
                <t-switch size="large" v-model="row.isInnerCompany" :label="['是', '否']" :customValue="['1', '0']"
                  @change="() => { row.name = '' }"></t-switch>
              </template>
              <template #name="{ row }">
                <t-tree-select :status="row.nameStatus"
                  @change="(val, content) => { row.companyId = content.node.data.id; if (row.name !== '') { row.nameStatus = 'default' } }"
                  v-if="row.isInnerCompany === '1'" style="width:390px" clearable filterable
                  :treeProps="{ keys: { value: 'label' } }" v-model="row.name" :data="deptMenuOptions"
                  placeholder="选择单位">
                  <div slot="tips" v-if="row.nameStatus === 'error'">不能为空</div>
                  <div slot="tips" v-else>搜索不到请切换外部单位后手输</div>
                  <template #label>
                    <t-switch size="medium" v-model="row.isInnerCompany" :label="['内部', '外部']" :customValue="['1', '0']"
                      @change="() => { row.name = ''; row.companyId = null; row.nameStatus = 'default' }"></t-switch>
                  </template>
                </t-tree-select>
                <t-select v-else v-model="row.name" creatable filterable placeholder="请输入" :status="row.nameStatus"
                  @change="(val, content) => { row.companyId = content.option?.id; if (row.name !== '') { row.nameStatus = 'default' } }"
                  :loading="companyLoading" @search="remoteCompanyMethod" :options="companyOptions"
                  @create="createCompanyOptions" style="width: 390px;display: inline-block">
                  <div slot="tips" v-if="row.nameStatus === 'error'">不能为空</div>
                  <div slot="tips" v-else>搜索不到请切换外部单位后手输</div>
                  <template #label>
                    <t-switch size="medium" v-model="row.isInnerCompany" :label="['内部', '外部']" :customValue="['1', '0']"
                      @change="() => { row.name = ''; row.companyId = null; row.nameStatus = 'default' }"></t-switch>
                  </template>
                </t-select>
              </template>
              <template #intro="{ row }">
                <t-textarea @change="() => { if (row.intro !== '') { row.introStatus = 'default' } }"
                  :status="row.introStatus" clearable :autosize="{ minRows: 3 }" v-model="row.intro">
                  <div slot="tips" v-if="row.introStatus === 'error'">不能为空</div>
                </t-textarea>
              </template>
              <template #leaderIntroduce="{ row }">
                <t-textarea
                  @change="() => { if (row.leaderIntroduce !== '') { row.leaderIntroduceStatus = 'default' } }"
                  :status="row.leaderIntroduceStatus" clearable :autosize="{ minRows: 3 }"
                  v-model="row.leaderIntroduce">
                  <div slot="tips" v-if="row.leaderIntroduceStatus === 'error'">不能为空</div>
                </t-textarea>
              </template>
              <template #division="{ row }">
                <t-textarea @change="() => { if (row.division !== '') { row.divisionStatus = 'default' } }"
                  :status="row.divisionStatus" clearable :autosize="{ minRows: 3 }" v-model="row.division">
                  <div slot="tips" v-if="row.divisionStatus === 'error'">不能为空</div>
                </t-textarea>
              </template>
              <template #bid="{ row }">
                <t-switch size="large" v-model="row.bid" :label="['是', '否']" :customValue="['1', '0']"></t-switch>
              </template>
              <template #op="{ row }">
                <file-upload :fileList="row?.sysAttMainEntities" :multiple="true" tips=""
                  v-model="row.sysAttMainVo.sysAttMainIds">
                  <t-button variant="outline">
                    <t-icon name="cloud-upload" slot="icon" />
                    点击上传
                  </t-button>
                </file-upload>
              </template>
            </t-table>
            <div v-if="!closeOp" style="margin-top: 10px" class="btn-group-inline">
              <t-button @click="addUnit">新增</t-button>
              <t-button @click="upUnit">上移</t-button>
              <t-button @click="downUnit">下移</t-button>
              <t-button @click="delUnit">删除</t-button>
            </div>
          </t-card>
        </t-col>
        <t-col v-else :span="12">
          <t-card class="step-card" size="small" title="合作单位">
            <t-table size="small" rowKey="id" :selected-row-keys="selectedUnitRowKeys"
              @select-change="(val) => { selectedUnitRowKeys = val }" :data="data6"
              :columns="phaseType !== '1' ? columns53 : columns5">
              <template #index="{ rowIndex }">
                {{ rowIndex + 1 }}
              </template>
              <template #isInnerCompany="{ row }">
                <t-switch size="large" v-model="row.isInnerCompany" :label="['是', '否']" :customValue="['1', '0']"
                  @change="() => { row.name = '' }"></t-switch>
              </template>
              <template #name="{ row }">
                <t-tree-select :status="row.nameStatus"
                  @change="(val, content) => { row.companyId = content.node.data.id; if (row.name !== '') { row.nameStatus = 'default' } }"
                  v-if="row.isInnerCompany === '1'" style="width:390px" clearable filterable
                  :treeProps="{ keys: { value: 'label' } }" v-model="row.name" :data="deptMenuOptions"
                  placeholder="选择单位">
                  <div slot="tips" v-if="row.nameStatus === 'error'">不能为空</div>
                  <div slot="tips" v-else>搜索不到请切换外部单位后手输</div>
                  <template #label>
                    <t-switch size="medium" v-model="row.isInnerCompany" :label="['内部', '外部']" :customValue="['1', '0']"
                      @change="() => { row.name = ''; row.companyId = null; row.nameStatus = 'default' }"></t-switch>
                  </template>
                </t-tree-select>
                <t-select v-else v-model="row.name" creatable filterable placeholder="请输入" :status="row.nameStatus"
                  @change="(val, content) => { row.companyId = content.option?.id; if (row.name !== '') { row.nameStatus = 'default' } }"
                  :loading="companyLoading" @search="remoteCompanyMethod" :options="companyOptions"
                  @create="createCompanyOptions" style="width: 390px;display: inline-block">
                  <div slot="tips" v-if="row.nameStatus === 'error'">不能为空</div>
                  <div slot="tips" v-else>搜索不到请切换外部单位后手输</div>
                  <template #label>
                    <t-switch size="medium" v-model="row.isInnerCompany" :label="['内部', '外部']" :customValue="['1', '0']"
                      @change="() => { row.name = ''; row.companyId = null; row.nameStatus = 'default' }"></t-switch>
                  </template>
                </t-select>
              </template>
              <template #intro="{ row }">
                <t-textarea @change="() => { if (row.intro !== '') { row.introStatus = 'default' } }"
                  :status="row.introStatus" clearable :autosize="{ minRows: 3 }" v-model="row.intro">
                  <div slot="tips" v-if="row.introStatus === 'error'">不能为空</div>
                </t-textarea>
              </template>
              <template #leaderIntroduce="{ row }">
                <t-textarea
                  @change="() => { if (row.leaderIntroduce !== '') { row.leaderIntroduceStatus = 'default' } }"
                  :status="row.leaderIntroduceStatus" clearable :autosize="{ minRows: 3 }"
                  v-model="row.leaderIntroduce">
                  <div slot="tips" v-if="row.leaderIntroduceStatus === 'error'">不能为空</div>
                </t-textarea>
              </template>
              <template #division="{ row }">
                <t-textarea @change="() => { if (row.division !== '') { row.divisionStatus = 'default' } }"
                  :status="row.divisionStatus" clearable :autosize="{ minRows: 3 }" v-model="row.division">
                  <div slot="tips" v-if="row.divisionStatus === 'error'">不能为空</div>
                </t-textarea>
              </template>
              <template #bid="{ row }">
                <t-switch size="large" v-model="row.bid" :label="['是', '否']" :customValue="['1', '0']"></t-switch>
              </template>
              <template #op="{ row }">
                <file-upload @change="(value, context) => { onUploadChange(value, context, row) }"
                  :status="row.fileStatus" :fileList.sync="row.sysAttMainEntities" :multiple="true" tips=""
                  v-model="row.sysAttMainVo.sysAttMainIds">
                  <t-button variant="outline">
                    <t-icon name="cloud-upload" slot="icon" />
                    点击上传
                  </t-button>
                  <div slot="tips" v-if="row.fileStatus === 'error'">不能为空</div>
                </file-upload>

              </template>
            </t-table>
            <div v-if="!closeOp" style="margin-top: 10px" class="btn-group-inline">
              <t-button @click="addUnit">新增</t-button>
              <t-button @click="upUnit">上移</t-button>
              <t-button @click="downUnit">下移</t-button>
              <t-button @click="delUnit">删除</t-button>
            </div>
          </t-card>
        </t-col>
      </t-row>
    </div>
    <div v-else>
      <t-row style="align-items: stretch" :gutter="14">
        <t-col :span="12">
          <t-card class="step-card" size="small" title="承担单位">
            <t-table size="small" rowKey="id" :data="data5" :columns="phaseType !== '1' ? columns544 : columns51">
              <template #index="{ rowIndex }">
                {{ rowIndex + 1 }}
              </template>
              <template #name="{ row, rowIndex }">
                <t-link @click="dialog.objId = row.companyId; dialog.header = row.name; dialog.open_detail = true"
                  hover="color" theme="primary">
                  <span
                    :style="{ color: diffData.length >= rowIndex + 1 && diffData[rowIndex].name !== row.name ? 'red' : '' }">{{
                      row.name }}</span>
                </t-link>
              </template>
              <template #intro="{ row, rowIndex }">
                <span
                  :style="{ color: diffData.length >= rowIndex + 1 && diffData[rowIndex].intro !== row.intro ? 'red' : '' }">{{
                    row.intro }}</span>
              </template>
              <template #division="{ row, rowIndex }">
                <span
                  :style="{ color: diffData.length >= rowIndex + 1 && diffData[rowIndex].division !== row.division ? 'red' : '' }">{{
                    row.division }}</span>
              </template>
              <template #leaderIntroduce="{ row, rowIndex }">
                <span
                  :style="{ color: diffData.length >= rowIndex + 1 && diffData[rowIndex].leaderIntroduce !== row.leaderIntroduce ? 'red' : '' }">{{
                    row.leaderIntroduce }}</span>
              </template>
            </t-table>
          </t-card>
        </t-col>
      </t-row>
      <t-row style="align-items: stretch" :gutter="14">
        <t-col v-if="site_tag === 'jtt'" :span="12">
          <t-card v-if="phaseType !== '1' || isShowTable" class="step-card" size="small" title="合作单位">
            <t-table size="small" rowKey="id" :selected-row-keys="selectedUnitRowKeys"
              @select-change="(val) => { selectedUnitRowKeys = val }" :data="data6"
              :columns="phaseType !== '1' ? columns54 : columns51">
              <template #id="{ rowIndex }">
                {{ rowIndex + 1 }}
              </template>
              <template #isInnerCompany="{ row, rowIndex }">
                <span
                  :style="{ color: diffData2.length >= rowIndex + 1 && diffData2[rowIndex].isInnerCompany !== row.isInnerCompany ? 'red' : '' }">{{
                    row.isInnerCompany
                      === '1' ? '是' : '否' }}</span>
              </template>
              <template #name="{ row, rowIndex }">
                <t-link @click="dialog.objId = row.companyId; dialog.header = row.name; dialog.open_detail = true"
                  hover="color" theme="primary">
                  <span
                    :style="{ color: diffData2.length >= rowIndex + 1 && diffData2[rowIndex].name !== row.name ? 'red' : '' }">{{
                      row.name }}</span>
                </t-link>
              </template>
              <template #intro="{ row, rowIndex }">
                <span
                  :style="{ color: diffData2.length >= rowIndex + 1 && diffData2[rowIndex].intro !== row.intro ? 'red' : '' }">{{
                    row.intro }}</span>
              </template>
              <template #division="{ row, rowIndex }">
                <span
                  :style="{ color: diffData2.length >= rowIndex + 1 && diffData2[rowIndex].division !== row.division ? 'red' : '' }">{{
                    row.division }}</span>
              </template>
              <template #leaderIntroduce="{ row, rowIndex }">
                <span
                  :style="{ color: diffData2.length >= rowIndex + 1 && diffData2[rowIndex].leaderIntroduce !== row.leaderIntroduce ? 'red' : '' }">{{
                    row.leaderIntroduce }}</span>
              </template>
              <template #bid="{ row, rowIndex }">
                <span
                  :style="{ color: diffData2.length >= rowIndex + 1 && diffData2[rowIndex].bid !== row.bid ? 'red' : '' }">{{
                    row.bid === '1' ? '是' : '否' }}</span>
              </template>
              <template #op="{ row }">
                <div v-if="row?.sysAttMainEntities?.length > 0">
                  <a class="t-button-link" target="_blank" v-for="(item, index) in row.sysAttMainEntities"
                    :href="item.fullFilePath" :key="index">
                    {{ item.name }}
                  </a>
                </div>
              </template>
            </t-table>
          </t-card>
        </t-col>
        <t-col v-else :span="12">
          <t-card class="step-card" size="small" title="合作单位">
            <t-table size="small" rowKey="id" :selected-row-keys="selectedUnitRowKeys"
              @select-change="(val) => { selectedUnitRowKeys = val }" :data="data6" :columns="columns51">
              <template #id="{ rowIndex }">
                {{ rowIndex + 1 }}
              </template>

              <template #isInnerCompany="{ row, rowIndex }">
                <span
                  :style="{ color: diffData2.length >= rowIndex + 1 && diffData2[rowIndex].isInnerCompany !== row.isInnerCompany ? 'red' : '' }">{{
                    row.isInnerCompany
                      === '1' ? '是' : '否' }}</span>
              </template>
              <template #name="{ row, rowIndex }">
                <t-link @click="dialog.objId = row.companyId; dialog.header = row.name; dialog.open_detail = true"
                  hover="color" theme="primary">
                  <span
                    :style="{ color: diffData2.length >= rowIndex + 1 && diffData2[rowIndex].name !== row.name ? 'red' : '' }">{{
                      row.name }}</span>
                </t-link>
              </template>
              <template #intro="{ row, rowIndex }">
                <span
                  :style="{ color: diffData2.length >= rowIndex + 1 && diffData2[rowIndex].intro !== row.intro ? 'red' : '' }">{{
                    row.intro }}</span>
              </template>
              <template #division="{ row, rowIndex }">
                <span
                  :style="{ color: diffData2.length >= rowIndex + 1 && diffData2[rowIndex].division !== row.division ? 'red' : '' }">{{
                    row.division }}</span>
              </template>
              <template #leaderIntroduce="{ row, rowIndex }">
                <span
                  :style="{ color: diffData2.length >= rowIndex + 1 && diffData2[rowIndex].leaderIntroduce !== row.leaderIntroduce ? 'red' : '' }">{{
                    row.leaderIntroduce }}</span>
              </template>
              <template #bid="{ row, rowIndex }">
                <span
                  :style="{ color: diffData2.length >= rowIndex + 1 && diffData2[rowIndex].bid !== row.bid ? 'red' : '' }">{{
                    row.bid === '1' ? '是' : '否' }}</span>
              </template>
              <template #op="{ row }">
                <div v-if="row?.sysAttMainEntities?.length > 0">
                  <a class="t-button-link" target="_blank" v-for="(item, index) in row.sysAttMainEntities"
                    :href="item.fullFilePath" :key="index">
                    {{ item.name }}
                  </a>
                </div>
              </template>
            </t-table>
          </t-card>
        </t-col>
      </t-row>
    </div>
    <unit-all-detail :header="dialog.header" :objId="dialog.objId" :visible.sync="dialog.open_detail"
      v-if="dialog.open_detail"></unit-all-detail>
  </div>

</template>

<script>
import FileUpload from "@/components/FileUpload/index.vue"
import { getFiles } from "@/api/common";
import unitAllDetail from "@/pages/common/system/components/unit-all-detail.vue";



export default {
  name: "item-unit",
  components: {
    FileUpload,
    unitAllDetail
  },
  props: {
    value: Array,
    projectId: [String, Number],
    editOpen: {
      type: Boolean,
      default: false
    },
    isShowTable: {
      type: Boolean,
      default: false
    },
    phaseType: {
      type: String,
      default: '1'
    },
    closeOp: {
      type: Boolean,
      default: false
    },
    useOldData: {
      type: Boolean,
      default: false
    },
    oldData: {
      type: Array,
      default: () => [],
    },
  },
  data () {
    return {
      dialog: {
        objId: null,
        header: '',
        open_detail: false,
      },
      site_tag: import.meta.env.VITE_SITE_TAG,
      data: [],
      diffData: [],
      diffData2: [],
      // adviceFunding: 0,
      companyLoading: false,
      companyOptions: [],
      deptMenuOptions: [],
      selectedUnitRowKeys: [],
      data5: [],
      columns5: [
        {
          colKey: 'row-select',
          type: 'single',
          title: "选择",
          checkProps: ({ row }) => ({ disabled: row.type === '1' }),
          width: 64
        },
        {
          colKey: 'index',
          title: "序号",
          align: "center",
          width: 50
        },
        // {
        //   colKey: "isInnerCompany",
        //   title: "是否内部单位",
        //   width: 120,
        // },
        {
          colKey: "name",
          title: "单位名称",
          align: "center",
          width: 200
        },
        // {
        //   colKey: "type",
        //   title: "单位类型",
        // },
        {
          colKey: "intro",
          title: "单位简介",
          align: "center",
          width: 300
        },
        {
          colKey: "division",
          title: "研究分工",
          align: "center",
          width: 200
        },
      ],
      columns53: [
        {
          colKey: 'row-select',
          type: 'single',
          title: "选择",
          checkProps: ({ row }) => ({ disabled: row.type === '1' }),
          width: 64
        },

        {
          colKey: 'index',
          title: "序号",
          align: "center",
          width: 50
        },
        // {
        //   colKey: "isInnerCompany",
        //   title: "是否内部单位",
        //   width: 120,
        // },
        {
          colKey: "name",
          title: "单位名称",
          align: "center",
          width: 200
        },
        // {
        //   colKey: "type",
        //   title: "单位类型",
        // },
        {
          colKey: "intro",
          title: "单位简介",
          align: "center",
          width: 300
        },
        {
          colKey: "division",
          title: "研究分工",
          align: "center",
          width: 200
        },
        // {
        //   colKey: "leaderIntroduce",
        //   title: "项目主要负责人简介",
        //   align: "center",
        //   width: 800
        // },
        {
          colKey: "bid",
          title: "是否招投标",
          align: "center",
          width: 100,
        },
        {
          colKey: "op",
          title: "合作协议",
          align: "center",
          width: 200,
        },
      ],
      columns52: [
        {
          colKey: 'row-select',
          type: 'single',
          title: "选择",
          checkProps: ({ row }) => ({ disabled: row.type === '1' }),
          width: 64
        },
        {
          colKey: 'index',
          title: "序号",
          align: "center",
          width: 50
        },
        {
          colKey: "name",
          title: "单位名称",
          align: "center",
          width: 200
        },
        // {
        //   colKey: "type",
        //   title: "单位类型",
        // },
        {
          colKey: "intro",
          title: "单位简介",
          align: "center",
          width: 300
        },
        {
          colKey: "division",
          title: "研究分工",
          align: "center",
          width: 200
        },
      ],
      columns522: [
        {
          colKey: 'row-select',
          type: 'single',
          title: "选择",
          checkProps: ({ row }) => ({ disabled: row.type === '1' }),
          width: 64
        },
        {
          colKey: 'index',
          title: "序号",
          align: "center",
          width: 50
        },
        {
          colKey: "name",
          title: "单位名称",
          align: "center",
          width: 200
        },
        // {
        //   colKey: "type",
        //   title: "单位类型",
        // },
        {
          colKey: "intro",
          title: "单位简介",
          align: "center",
          width: 300
        },
        {
          colKey: "division",
          title: "研究分工",
          align: "center",
          width: 200
        },
        // {
        //   colKey: "leaderIntroduce",
        //   title: "项目主要负责人简介",
        //   align: "center",
        //   width: 800
        // },
      ],
      columns51: [
        {
          colKey: 'index',
          title: "序号",
          align: "center",
          width: 50
        },
        {
          colKey: "name",
          title: "单位名称",
          align: "center",
          width: 200
        },
        // {
        //   colKey: "type",
        //   title: "单位类型",
        // },
        {
          colKey: "intro",
          title: "单位简介",
          align: "center",
          width: 300
        },
        {
          colKey: "division",
          title: "研究分工",
          align: "center",
          width: 200
        },
        // {
        //   colKey: "leaderIntroduce",
        //   title: "主要负责人简介",
        //   align: "center"
        // },
      ],
      columns54: [
        {
          colKey: 'index',
          title: "序号",
          align: "center",
          width: 50
        },
        // {
        //   colKey: "isInnerCompany",
        //   title: "是否内部单位",
        //   width: 120,
        // },
        {
          colKey: "name",
          title: "单位名称",
          align: "center",
          width: 200
        },
        // {
        //   colKey: "type",
        //   title: "单位类型",
        // },
        {
          colKey: "intro",
          title: "单位简介",
          align: "center",
          width: 300
        },
        {
          colKey: "division",
          title: "研究分工",
          align: "center",
          width: 200
        },
        // {
        //   colKey: "leaderIntroduce",
        //   title: "项目主要负责人简介",
        //   align: "center",
        //   width: 800
        // },
        {
          colKey: "bid",
          title: "是否招投标",
          align: "center",
          width: 100,
        },
        {
          colKey: "op",
          title: "合作协议",
          align: "center",
          width: 200,
        },
      ],
      columns544: [
        {
          colKey: 'index',
          title: "序号",
          align: "center",
          width: 50
        },
        // {
        //   colKey: "isInnerCompany",
        //   title: "是否内部单位",
        //   width: 120,
        // },
        {
          colKey: "name",
          title: "单位名称",
          align: "center",
          width: 200
        },
        // {
        //   colKey: "type",
        //   title: "单位类型",
        // },
        {
          colKey: "intro",
          title: "单位简介",
          align: "center",
          width: 300
        },
        {
          colKey: "division",
          title: "研究分工",
          align: "center",
          width: 200
        },
        // {
        //   colKey: "leaderIntroduce",
        //   title: "项目主要负责人简介",
        //   align: "center",
        //   width: 800
        // },
      ],
      data6: [],
    }
  },
  watch: {
    value: {
      deep: true,
      immediate: true,
      handler (val) {
        if (val && val.length > 0 && this.useOldData) {
          let newArr = val.map(data => {
            return {
              ...data,
              initType: 'init'
            }
          })
          // 防止无限循环，简单比较一下
          if (JSON.stringify(val) !== JSON.stringify(this.data)) {
            this.data = newArr;
            this.data5 = this.data.filter((val) => val.type === '1');
            this.data6 = this.data.filter((val) => val.type === '2');
          }
        }
      }
    },
    projectId: {
      immediate: true,
      handler (val) {
        if (val) {
          this.getUnit(val);
        }
      }
    },
    data5: {
      deep: true,
      immediate: true,
      handler (val) {
        const data = this.data5.concat(this.data6).map((val) => ({ ...val, phaseType: this.phaseType }))
        const newData = data.map((val, index) => ({ ...val, sort: index + 1 }))
        this.$emit("input", newData);
      }
    },
    data6: {
      deep: true,
      immediate: true,
      handler (val) {
        const data = this.data5.concat(this.data6).map((val) => ({ ...val, phaseType: this.phaseType }))
        const newData = data.map((val, index) => ({ ...val, sort: index + 1 }))
        this.$emit("input", newData);
      }
    },
    oldData: {
      deep: true,
      immediate: true,
      handler (val) {
        this.diffData = val.filter((val) => val.type === '1');
        this.diffData2 = val.filter((val) => val.type === '2');
      }
    },
  },
  created () {
    // 获取项目详情
    this.getDeptTreeSelect(this.$store.state.user.deptId)
  },
  methods: {
    onUploadChange (value, context, row) {
      this.$nextTick(() => {
        if (row.sysAttMainVo?.sysAttMainIds?.length > 0) {
          row.fileStatus = 'default'
        }
      })
    },
    createCompanyOptions (value) {
      this.companyOptions.push({
        label: `${value}`,
        value,
      });
    },
    remoteCompanyMethod (search) {
      this.companyLoading = true;
      this.$api.system.dept.selectAllOutDeptList({ deptName: search }).then(response => {
        this.companyOptions = response.data.map(val => ({
          ...val,
          label: `${val.deptName}`,
          value: val.deptName,
        }));
        this.companyLoading = false;
      }).catch((e) => {
        this.companyLoading = false;
        this.$message.error(e.toString());
      });
    },
    onDeptChange (value, row) {
      if (row.name !== '') {
        row.nameStatus = 'default'
      }
      if (row.intro === '') {
        this.$api.system.dept.list({ deptName: value }).then(response => {
          if (response.data.length > 0) {
            row.intro = response.data[0].deptProfile ? response.data[0].deptProfile : '';
          }
        }).catch((e) => {
          this.$message.error(e.toString());
        });
      }
    },
    checkData () {
      if (this.data5.length <= 0) {
        this.$message.error("承担单位不能为空");
        return false;
      }
      if (!this.data5[0].intro) {
        this.$set(this.data5[0], 'introStatus', 'error')
        this.$message.error("承担单位：简介不能为空");
        return false;
      }
      this.$set(this.data5[0], 'introStatus', 'default')
      if (!this.data5[0].division) {
        this.$set(this.data5[0], 'divisionStatus', 'error')
        this.$message.error("承担单位：研究分工不能为空");
        return false;
      }
      this.$set(this.data5[0], 'divisionStatus', 'default')
      // if (!this.data5[0].leaderIntroduce && this.phaseType !== '1') {
      //   this.$set(this.data5[0], 'leaderIntroduceStatus', 'error')
      //   this.$message.error("承担单位：主要负责人简介不能为空");
      //   return false;
      // }
      // this.$set(this.data5[0], 'leaderIntroduceStatus', 'default')

      // 合作单位 非空判断
      const isValidate = this.data6.every((val, index) => {
        if (!val.name) {
          this.$set(this.data6[index], 'nameStatus', 'error')
          this.$message.error(`合作单位：第${index + 1}条"单位名称"不能为空`);
          return false;
        }
        this.$set(this.data6[index], 'nameStatus', 'default')
        if (!val.intro) {
          this.$set(this.data6[index], 'introStatus', 'error')
          this.$message.error(`合作单位：第${index + 1}条"单位简介"不能为空`);
          return false;
        }
        this.$set(this.data6[index], 'introStatus', 'default')
        if (!val.division) {
          this.$set(this.data6[index], 'divisionStatus', 'error')
          this.$message.error(`合作单位：第${index + 1}条"单位分工"不能为空`);
          return false;
        }
        this.$set(this.data6[index], 'divisionStatus', 'default')
        // if (!val.leaderIntroduce && this.phaseType !== '1') {
        //   this.$set(this.data6[index], 'leaderIntroduceStatus', 'error')
        //   this.$message.error(`合作单位：第${index + 1}条"主要负责人简介"不能为空`);
        //   return false;
        // }
        // this.$set(this.data6[index], 'leaderIntroduceStatus', 'default')
        // 判断是否上传合作协议
        if (this.phaseType === '3') {
          if ((val.sysAttMainVo?.sysAttMainIds && val.sysAttMainVo?.sysAttMainIds?.length <= 0) || !val.sysAttMainVo?.sysAttMainIds) {
            this.$set(this.data6[index], 'fileStatus', 'error')
            this.$message.error(`合作单位：第${index + 1}条"合作协议"不能为空`);
            return false;
          }
          this.$set(this.data6[index], 'fileStatus', 'default')
        }
        return true;
      });
      return isValidate;
    },
    deptChange (value, row) {
      row.name = value || row.name;
      if (row.name !== '') {
        row.nameStatus = 'default'
      }
    },
    getDeptTreeSelect (id) {
      return this.$api.system.dept.treeSelectAllIn().then(response => {
        this.deptMenuOptions = response.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    getUnit () {
      // 显示外层带的数据不查询
      if (this.useOldData) {
        return false;
      }
      if (this.projectId) {
        this.$api.kjxm.project.companyGet(this.projectId, this.phaseType).then(response => {
          response.data = response.data.map((row, index) => ({
            ...row,
            index,
            sysAttMainVo: {
              sysAttMainIds: row?.sysAttMainVo?.sysAttMainIds || []
            },
            sysAttMainEntities: row.sysAttMainEntities?.map(val => {
              return {
                ...val, name: val.fileName, url: val.fullFilePath,
                fullFilePath: val.fullFilePath, id: val.id, filePath: val.filePath
              }
            }),
          }));
          this.data5 = response.data.filter((val) => val.type === '1');
          this.data6 = response.data.filter((val) => val.type === '2');
          if (this.data5.length <= 0) {
            const newId = Number(new Date().getTime()) + Number(Math.random() * 10)
            // 添加默认承担单位
            this.data5 = [{
              projectId: this.projectId,
              name: this.$store.state.user.deptName,
              intro: '',
              division: '',
              type: '1',
              phaseType: this.phaseType,
              id: newId,
              isInnerCompany: '1',
              leaderIntroduce: ''
            }];
            const data = this.data5.concat(this.data6).map((val) => ({ ...val, phaseType: this.phaseType }))
            const newData = data.map((val, index) => ({ ...val, sort: index + 1 }))
            this.$emit("input", newData);
          } else {
            const data = this.data5.concat(this.data6).map((val) => ({ ...val, phaseType: this.phaseType }))
            const newData = data.map((val, index) => ({ ...val, sort: index + 1 }))
            this.$emit("input", newData);
          }
          // 如果数组为空则查项目的
          if (response.data.length <= 0 && this.phaseType !== '1' && this.editOpen === true) {
            let lastStep = Number(this.phaseType) - 1 > 0 ? Number(this.phaseType) - 1 : 1
            if (this.phaseType === '3') {
              lastStep = 1
            } else if (this.phaseType === '31') {
              lastStep = 3;
            }
            this.$api.kjxm.project.companyGet(this.projectId, lastStep).then(response2 => {
              response2.data = response2.data.map((row, index) => ({ ...row, index }));
              this.data5 = response2.data.filter((val) => val.type === '1');
              this.data6 = response2.data.filter((val) => val.type === '2');
              if (this.data5.length <= 0) {
                const newId = Number(new Date().getTime()) + Number(Math.random() * 10)
                // 添加默认承担单位
                this.data5 = [{
                  projectId: this.projectId,
                  name: this.$store.state.user.deptName,
                  intro: '',
                  division: '',
                  type: '1',
                  phaseType: this.phaseType,
                  id: newId,
                  isInnerCompany: '1',
                  leaderIntroduce: ''
                }];
                const data = this.data5.concat(this.data6).map((val) => ({ ...val, phaseType: this.phaseType }))
                const newData = data.map((val, index) => ({ ...val, sort: index + 1 }))
                this.$emit("input", newData);
              } else {
                const data = this.data5.concat(this.data6).map((val) => ({ ...val, phaseType: this.phaseType }))
                const newData = data.map((val, index) => ({ ...val, sort: index + 1 }))
                this.$emit("input", newData);
              }

            }).catch((e) => {
              this.$message.error(e.toString());
            });
          }
        }).catch((e) => {
          this.$message.error(e.toString());
        });
      }
    },
    moveInArray (arr, ffrom, to) {
      // 删除当前的位置
      const item = arr.splice(ffrom, 1);
      // 确保还剩有元素移动
      if (!item.length) {
        this.$message.warning(`There is no item in the array at index ${ffrom}`);
      }
      // 移动元素到指定位置
      arr.splice(to, 0, item[0]);
    },
    addUnit () {
      this.data6.push({
        projectId: this.projectId,
        name: '',
        intro: '',
        division: '',
        type: '2',
        phaseType: this.phaseType,
        id: Date.parse(new Date()),
        bid: "0",
        isInnerCompany: '1',
        companyId: null,
        sysAttMainVo: {
          sysAttMainIds: [],
        }
      })
    },
    upUnit () {
      if (this.selectedUnitRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      if (this.data6[0].id === this.selectedUnitRowKeys[0]) {
        this.$message.warning("已是第一行");
      } else {
        const index = this.data6.findIndex((val) => val.id === this.selectedUnitRowKeys[0])
        this.moveInArray(this.data6, index, index - 1)
      }
    },
    downUnit () {
      if (this.selectedUnitRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      if (this.data6[this.data6.length - 1].id === this.selectedUnitRowKeys[0]) {
        this.$message.warning("已是最后一行");
      } else {
        const index = this.data6.findIndex((val) => val.id === this.selectedUnitRowKeys[0])
        this.moveInArray(this.data6, index, index + 1)
      }
    },
    delUnit () {
      if (this.selectedUnitRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      const index = this.data6.findIndex((val) => val.id === this.selectedUnitRowKeys[0])
      this.data6.splice(index, 1);
      this.selectedUnitRowKeys = [];
    },
  }
}
</script>

<style lang="less" scoped>
.step-form {
  padding: 0 24px;
}

.t-row {
  margin-bottom: 14px;
}

.step-card {
  height: 100%;
  margin-bottom: 14px;
  overflow: scroll;
}
</style>
